package com.apes.fn.scm.retailOrder.service.retailProcess.process;

import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.service.retailProcess.CommonRetailDataProcess;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.model.UsageBusiness;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.masterdata.stock.repository.UsageBusinessRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 普通的零售订单
 *
 * @author wuq
 * @create 2021-05-21 16:57
 */
@Service
public class GeneralOrderProcess extends CommonRetailDataProcess {

    @Autowired
    private ProductUomRepository productUomRepository;
    @Autowired
    private UsageBusinessRepository usageBusinessRepository;
    @Autowired
    private LocationRepository locationRepository;

    @Override
    public void beforeSave(RetailOrder retailOrder) {
        beforeProcess(retailOrder, this::updateRetailItem);
    }

    private void updateRetailItem(RetailOrder retailOrder) {
        retailOrder.getSaleItems().forEach(item -> {
            String uomName = item.getUomName();
            List<ProductUom> list = productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", item.getProduct().getId()))
                    .stream().filter(p -> p.getName().equals(uomName)).collect(Collectors.toList());
            if (list.size() == 0) throw new RuntimeException("获取计量单位失败,请检查商品：" + item.getProduct().getId() + "：是否存在设置了计量单位");

            item.setUom(list.get(0));
            List<UsageBusiness> ulist = usageBusinessRepository.findAll(JpaDsl.toCriteriaByEq("businessType.id", "RetailOrder"));
            if (ulist.size() == 0) throw new RuntimeException("未找到零售单配置的库区属性！");

            UsageBusiness usageBusiness = ulist.get(0);
            List<Location> location = locationRepository.findAll(JpaDsl.toCriteriaByEq("depot.dept.id", retailOrder.getDept().getId(), "usage.id", usageBusiness.getUsage().getId()));
            if (location.size() == 0) throw new RuntimeException("该部门正常库未配置，请配置");
            item.setLocation(location.get(0));
        });
    }

    @Override
    public void afterSave(RetailOrder retailOrder) {
        setProductAvailable(retailOrder, -1, "零售订单生成");        //占用可用数
    }

    @Override
    public boolean support(String orderType) {
        return "generalOrder".equals(orderType);
    }
}
